package com.feijia.aijingjingus;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.timqi.sectorprogressview.ColorfulRingProgressView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.feijia.aijingjingus.GlobalHelper.AssociatedUser;
import static com.feijia.aijingjingus.GlobalHelper.DaysBeforeOvulation;
import static com.feijia.aijingjingus.GlobalHelper.FirstDay;
import static com.feijia.aijingjingus.GlobalHelper.GUserNum;
import static com.feijia.aijingjingus.GlobalHelper.Menstruation;
import static com.feijia.aijingjingus.GlobalHelper.NickName;
import static com.feijia.aijingjingus.GlobalHelper.ONE_DAY_MS;
import static com.feijia.aijingjingus.GlobalHelper.OvulationLength;
import static com.feijia.aijingjingus.GlobalHelper.PeriodLength;
import static com.feijia.aijingjingus.GlobalHelper.Sex;
import static com.feijia.aijingjingus.GlobalHelper.handler;

public class ManMainActivity extends AppCompatActivity {
    private OptionsPickerView pvInputAssociatedCode,pvLogout;
    private Context context;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private Calendar c;
    private ScrollView scrollView1;
    private RelativeLayout rlNoData;
    private TextView tvShowDate2, tvDateDetail, tvPercent;
    private SharedPreferences sp;
    ColorfulRingProgressView crpv;
    private ListView lvAllDetection;
    private List<Map<String, Object>> historyData;
    private boolean binding = false;
    final Runnable showGirlData = new Runnable() {
        @Override
        public void run() {
            //更新界面
            int y = scrollView1.getScrollY();
            SimpleAdapter adapter = new SimpleAdapter(context, historyData, R.layout.man_page_detection_view,
                    new String[]{"value", "date", "month", "year", "img", "data"},
                    new int[]{R.id.value, R.id.tvDate, R.id.tvMonth, R.id.tvYear, R.id.resultimg, R.id.data});
            lvAllDetection.setAdapter(adapter);
            lvAllDetection.setVisibility(View.VISIBLE);
            if (historyData.size() == 0)
                rlNoData.setVisibility(View.VISIBLE);
            lvAllDetection.setFocusable(false);
            ViewGroup.LayoutParams params = lvAllDetection.getLayoutParams();
            params.height = historyData.size() * 500;
            lvAllDetection.setLayoutParams(params);
            scrollView1.smoothScrollTo(0, y);
        }

    };
    final Runnable updateDateDetail = new Runnable() {
        @Override
        public void run() {
            try {
                Date date = c.getTime();
                tvShowDate2.setText(SimpleDateFormat.getDateInstance().format(date));
                Calendar cl = Calendar.getInstance();
                cl.setTime(date);
                long nowDay = (cl.getTimeInMillis() / ONE_DAY_MS) % Menstruation;
                date = sdf.parse(FirstDay);
                cl.setTime(date);
                long firstDay = (cl.getTimeInMillis() / ONE_DAY_MS) % Menstruation;
                nowDay -= firstDay;
                if (nowDay < 0)
                    nowDay += Menstruation;
                cl.add(Calendar.DAY_OF_MONTH, PeriodLength);
                long firstDayAfterPeriod = (cl.getTimeInMillis() / ONE_DAY_MS) % Menstruation - firstDay;
                long firstDayOfOvulation = DaysBeforeOvulation;
                long lastDayOfOvulation = firstDayOfOvulation + OvulationLength;
                long lastDay = firstDay + Menstruation - firstDay;
                firstDay = 0;

                String str;
                int days;
                int PregnancyProbability = 15;
                System.out.println("nowDay:" + nowDay + "  firstDayAfterPeriod:" + firstDayAfterPeriod + "  firstDayOfOvulation:" + firstDayOfOvulation + "  lastDayOfOvulation:" + lastDayOfOvulation + "  lastDay:" + lastDay + "  firstDay:" + firstDay);
                if (nowDay >= firstDay && nowDay < firstDayAfterPeriod) {
                    days = (int) ((nowDay - firstDay)) + 1;
                    PregnancyProbability = 10;
                    str = String.format(getString(R.string.DayOfMenstrualPeriod_html), days);
                    //str = "This is the day <font color=\"#FF3366\">2</font> of the menstrual period.";
                    System.out.println(str);
                } else if (nowDay >= firstDayAfterPeriod && nowDay < firstDayOfOvulation) {
                    days = (int) ((firstDayOfOvulation - nowDay));
                    if (days == 1)
                        str = getString(R.string.DayBeforeOvulation_html);
                    else
                        str = String.format(getString(R.string.DaysBeforeOvulation_html), days);
                } else if (nowDay >= firstDayOfOvulation && nowDay < lastDayOfOvulation) {
                    days = (int) ((nowDay - firstDayOfOvulation)) + 1;
                    str = String.format(getString(R.string.DayOfOvulation_html), days);
                    PregnancyProbability = 90 - Math.abs(days - OvulationLength / 2) * 15;
                } else if (nowDay >= lastDayOfOvulation && nowDay < lastDay) {
                    days = (int) ((lastDay - nowDay));
                    str = String.format(getString(R.string.DaysBeforePeriod_html), days);
                } else {
                    days = (int) ((firstDay - nowDay));
                    if (days == 1)
                        str = getString(R.string.DayBeforePeriod_html);
                    else
                        str = String.format(getString(R.string.DaysBeforePeriod_html), days);
                }
                //str=""+days;
                tvDateDetail.setText(Html.fromHtml(str));
                ObjectAnimator crpvChange = ObjectAnimator.ofFloat(crpv, "Percent", crpv.getPercent(), PregnancyProbability).setDuration(500);
                crpvChange.start();
                //crpv.setPercent(PregnancyProbability);
                str = "" + PregnancyProbability + "%";
                SpannableStringBuilder style = new SpannableStringBuilder(str);
                AbsoluteSizeSpan span = new AbsoluteSizeSpan(37, true);
                style.setSpan(span, 0, 2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                tvPercent.setText(style);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_man_main);
        context = this;
        scrollView1 = (ScrollView) findViewById(R.id.scrollView1);
        rlNoData = (RelativeLayout) findViewById(R.id.rlNoData);
        lvAllDetection = (ListView) findViewById(R.id.allDetection);
        crpv = (ColorfulRingProgressView) findViewById(R.id.crpv);
        tvShowDate2 = (TextView) findViewById(R.id.tvShowDate2);
        tvDateDetail = (TextView) findViewById(R.id.tvDateDetail);
        tvPercent = (TextView) findViewById(R.id.tvPercent);
        c = Calendar.getInstance();
        sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        if (AssociatedUser.isEmpty()) {
            BindGirl();
        } else {
            GetGirlData();
        }
    }

    private void BindGirl() {
        pvInputAssociatedCode = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                //String tx = cardItem.get(options1).getPickerViewText();
                //btn_CustomOptions.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_bind_girl_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        final EditText etAssociatedCode = (EditText) v.findViewById(R.id.etAssociatedCode);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (etAssociatedCode.getText().length() != 0) {
                                    if (!binding) {
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                binding = true;
                                                handler.post(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Toast.makeText(context, context.getString(R.string.binding_str), Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                                JSONObject root = new JSONObject();
                                                try {
                                                    root.put("UserNo", Long.parseLong(GUserNum));
                                                    root.put("AssociatedCode", etAssociatedCode.getText().toString());
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                                final JSONObject out = GlobalHelper.PostData(root, "http://aaaaahealth.com/ting/bindGirl.php");
                                                System.out.println(out);
                                                binding = false;
                                                if (out == null) {
                                                    handler.post(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            Toast.makeText(context, context.getString(R.string.networkConnectionFailed), Toast.LENGTH_SHORT).show();
                                                        }
                                                    });
                                                    return;
                                                } else {
                                                    handler.post(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            try {
                                                                if (out.getInt("OperateResult") == 1) {
                                                                    Toast.makeText(context, context.getString(R.string.BindSuccess_str), Toast.LENGTH_SHORT).show();
                                                                    pvInputAssociatedCode.returnData();
                                                                    pvInputAssociatedCode.dismiss();
                                                                    GetGirlData();
                                                                }else {
                                                                    Toast.makeText(context, context.getString(R.string.BindFail_str), Toast.LENGTH_SHORT).show();
                                                                }
                                                            } catch (JSONException e) {
                                                                e.printStackTrace();
                                                            }
                                                        }
                                                    });
                                                }

                                            }
                                        }).start();
                                    }
                                } else {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(context, context.getString(R.string.FeedbackCantEmpty), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }

                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvInputAssociatedCode.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();
        pvInputAssociatedCode.show();
    }


    private void GetGirlData() {
        ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        // 检查网络连接，如果无网络可用，就不需要进行连网操作等
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info == null || !manager.getBackgroundDataSetting()) {
            Toast.makeText(context, context.getString(R.string.networkConnectionFailed), Toast.LENGTH_SHORT).show();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject root = new JSONObject();
                try {
                    root.put("UserNo", Long.parseLong(GUserNum));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                JSONObject out = GlobalHelper.PostData(root, "http://120.77.255.57/ting/getUserData.php");
                if (out == null) {
                    Toast.makeText(context, context.getString(R.string.networkConnectionFailed), Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
            /*if (!out.isNull("Age")) {
                Age = out.getInt("Age");
            }*/
                    if (!out.isNull("StartDay")) {
                        FirstDay = out.get("StartDay").toString();
                    }
                    if (!out.isNull("Menstruation")) {
                        Menstruation = out.getInt("Menstruation");
                    }
                    if (!out.isNull("PeriodLength")) {
                        PeriodLength = out.getInt("PeriodLength");
                    }
                    if (!out.isNull("AssociatedUser")) {
                        AssociatedUser = out.getString("AssociatedUser");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                handler.post(updateDateDetail);
                historyData = getData(sdf.format(c.getTime()));
                handler.post(showGirlData);
            }
        }).start();
    }

    private List<Map<String, Object>> getData(String date) {
        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> map;
        if (date == null)
            date = sdf.format(c.getTime());
        Log.v("date", date);
        JSONObject root = new JSONObject();
        try {
            root.put("UserNo", Long.parseLong(AssociatedUser) /*Long.parseLong(GUserNum)*/);
            root.put("DetectionDateStart", date);
            root.put("DetectionDateEnd", date);
            System.out.println("getDetections:" + root);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JSONObject out = GlobalHelper.PostData(root, "http://aaaaahealth.com/ting/getDetections.php");
        System.out.println("getDetections:" + out);
        try {
            if (!out.isNull("OperateResult")&&out.getInt("OperateResult") == 1) {
                String OperateMsg = out.getString("OperateMsg"); // 获取操作结果信息
                System.out.printf(" OperateResult : %s \n OperateMsg : %s\n", out.getInt("OperateResult"), OperateMsg);
                //JSONObject result = new JSONObject(out.getString("OperateMsg"));
                for (int i = 0; i < out.getInt("ResultCount"); i++) {
                    JSONObject historyObject = new JSONObject(out.getString("" + i));
                    map = new HashMap<>();

                    Date tempdate = sdf.parse(historyObject.get("DetectionDate").toString());
                    map.put("date", tempdate.getDate());
                    map.put("month", tempdate.getMonth());
                    map.put("year", tempdate.getYear()-100);
                    if (historyObject.get("type").equals("LH")) {
                        String temp = getResources().getString(R.string.Ovulation_more_str);
                        String temp2 = String.format(temp, historyObject.getInt("DetectionResults"));
                        if (historyObject.getInt("DetectionResults") <= 72)
                            temp2 = getString(R.string.Ovulation_near);
                        if (historyObject.getInt("DetectionResults") > 72)
                            temp2 = getString(R.string.Ovulation_far);
                        map.put("value", temp2);

                        map.put("img", R.color.zero);
                        map.put("data", "LH: " + (int) (historyObject.getDouble("RawDetectionData")) + " mIU/L");
                    } else {
                        if (historyObject.get("DetectionResults").equals("" + 0)) {
                            map.put("value", context.getString(R.string.NotPregnanted_str));
                            map.put("img", R.drawable.cross);
                        } else {
                            map.put("value", context.getString(R.string.Pregnanted_str));
                            map.put("img", R.drawable.check);
                        }
                        map.put("data", "HCG: " + (int) (historyObject.getDouble("RawDetectionData")) + " mIU/L");
                    }
                    list.add(map);
                }
            } else {
                System.out.println("predict error");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }
    public void onClickLogout(View view) {
        pvLogout = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                //String tx = cardItem.get(options1).getPickerViewText();
                //btn_CustomOptions.setText(tx);
                SharedPreferences.Editor editor = sp.edit();
                //editor.putString("USER_NAME", "");
                editor.clear();
                editor.apply();
                Intent intent = new Intent("MainActivity");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_logout_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        final TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                        final EditText etDialogNickName = (EditText) v.findViewById(R.id.etDialogNickName);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvLogout.returnData();
                                pvLogout.dismiss();
                            }
                        });

                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvLogout.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();
        pvLogout.setPicker(new ArrayList<>());//添加数据
        pvLogout.show();
    }
}
